from bottle import route,run,error,static_file,request,response,template,redirect
from db import setupDb,Stu,StuSbjct,StuAnswr,AskHelps,HlpAnswrs
from tools.verify_gen import get_verify

secret = 'df##%^$$EWFFDSFDG^%$&^&()(&^^$TQ#TG'
@error(404)
def err(err):
    return '404'

@route('/static/<filename:re:.*.[jpg|jpeg|png]$>')
def getPic(filename):
    return static_file(filename,root="./img")

@route('/static/<filename:re:.*.[css]$>')
def getPic(filename):
    return static_file(filename,root="./css")

@route('/',method=['GET','POST'])
@route('/<sid:int>',method=['GET','POST'])
def index(sid=1):
    sbjct = StuSbjct()
    sbjcts = sbjct.getSbjcts()
    askhlps = getHlps()
    self_answr = None
    if request.method == 'GET':
        name = request.get_cookie('name',secret=secret)
        id = request.get_cookie('id',secret=secret)
        usertype = request.get_cookie('usertype',secret=secret)
        if name and id and sid:
            self_answr = getselfAnswr(sid,id)
        return template('tpls/index.tpl',
            name=name,
            id=id,
            usertype=usertype,
            sbjcts=sbjcts,
            current_sbjct=get_current_sbjct(sid,sbjcts),
            askhlps=askhlps,
            self_answr=self_answr,
            sid=sid,
            )
    elif request.method == 'POST':
        verify_text = request.get_cookie('verify_text',secret=secret)
        response.delete_cookie('verify_text')
        sid = int(request.forms.getunicode('sid'))
        if verify_text and verify_text.lower() == request.forms.getunicode('verify_text').lower().strip():
            s = Stu(name=request.forms.getunicode('name').strip(),
                psswd=request.forms.getunicode('psswd').strip())
            res = s.isRgstr()
            print(res)
            if res:
                self_answr = getselfAnswr(sid,res[0])
                response.set_cookie('name',res[1],secret=secret)
                response.set_cookie('id',res[0],secret=secret)
                response.set_cookie('usertype',res[3],secret=secret)
                return template('tpls/index.tpl',
                    name = res[1],
                    id = res[0],
                    usertype = res[3],
                    sbjcts=sbjcts,
                    current_sbjct=get_current_sbjct(sid,sbjcts),
                    askhlps=askhlps,
                    self_answr=self_answr,
                    sid=sid,
                    )
        redirect('/%s' % sid)

def get_current_sbjct(sid,sbjcts):
    for sbjct in sbjcts:
        if sid == sbjct[0]:
            return sbjct

def getHlps():
    res = AskHelps().getLastQstns()
    hlpanswr = HlpAnswrs()
    re = [[item,hlpanswr.getAnswrs(item[0])] for item in res]
    return re

def getselfAnswr(sbjct_id,stu_id):
    return StuAnswr().getSelfAnswr(sbjct_id,stu_id)

@route('/logout')
def lgt():
    cookie_names = ('name','id','usertype')
    for cookie_name in cookie_names:
        response.delete_cookie(cookie_name)
    redirect('/')

@route('/signup',method=['GET','POST'])
def sign():
    if request.method=='GET':
        info = request.query.info
        return template('tpls/signup.tpl',info=info)
    elif request.method=='POST':
        info=''
        verify_text = request.get_cookie('verify_text',secret=secret)
        response.set_cookie('verify_text','',secret=secret)
        if verify_text and verify_text.lower() == request.forms.getunicode('verify_text').lower().strip():
            name = request.forms.getunicode('name').strip()
            psswd = request.forms.getunicode('psswd').strip()
            psswdb = request.forms.getunicode('psswdb').strip()
            if name and psswd and psswd==psswdb:
                s = Stu(name=name,psswd=psswd)
                if s.save():
                    res = s.isRgstr()
                    response.set_cookie('name',res[1],secret=secret)
                    response.set_cookie('id',res[0],secret=secret)
                    response.set_cookie('usertype',res[3],secret=secret)
                    response.set_cookie('verify_text','',secret=secret)
                    redirect('/')
                else:
                    info='注册用户信息失败！'
            else:
                info = '用户名或密码不能为空/密码不匹配!'
        else:
            info = '验证码错误！'
        redirect('/signup?info=%s' % info)

@route('/verify')
def verify():
    img,text = get_verify()
    response.set_cookie('verify_text',text,secret=secret)
    return img

## 以上直接从案例1中直接复制过来的代码
## 包括注册、登录、验证码、退出等功能
##管理学习主题的问题
@route('/mgr_sbjcts/<sid:int>')
@route('/mgr_sbjcts',method=['GET','POST'])
def mgr_sbjcts(sid=0):
    usertype = request.get_cookie('usertype',secret=secret)
    if usertype != 1:
        redirect('/')
        return
    sbjct = StuSbjct()
    if sid:
        sbjct.delete(sid)
        redirect('/mgr_sbjcts')
        return
    sbjcts = sbjct.getSbjcts()
    if request.method=="GET":        
        return template('tpls/mgr_sbjcts.tpl',sbjcts=sbjcts)
    if request.method=="POST":
        title = request.forms.getunicode('title').strip()
        qstn = request.forms.getunicode('qstn').strip()
        if title and qstn:
            StuSbjct(title=title,qstn=qstn).save()
        redirect('/mgr_sbjcts')

#接收学员提交的答案，并存入数据库
@route('/add_qstn',method="POST")
def add_qstn():
    sid = int(request.forms.getunicode('sid'))
    answr = request.forms.getunicode('answr').strip()
    stu_id = request.forms.getunicode('id')
    StuAnswr(stu_id=id,sbjct_id=sid,answr=answr).save()
    redirect('/%s' % sid)

#接收提交的需要讨论的问题，并存入数据库
@route('/ask_help',method="POST")
def ask_help():
    sid = int(request.forms.getunicode('sid'))
    stu_id = request.forms.getunicode('id')
    qstn = request.forms.getunicode('qstn').strip()
    AskHelps(stu_id=stu_id,qstn=qstn).save()
    redirect('/%s' % sid)

#接收提交的对讨论主题的回答，并存入数据库
@route('/add_answr',method="POST")
def add_answr():
    sid = int(request.forms.getunicode('sid'))
    id = request.forms.getunicode('id')
    ask_id = request.forms.getunicode('ask_id')
    answr = request.forms.getunicode('answr').strip()
    HlpAnswrs(ask_id=ask_id,hlper_id=id,answr=answr).save()
    redirect('/%s' % sid)

if __name__ == "__main__":
    setupDb()
    run(port=80,debug=True,reloader=True)